package com.better.common.exception;

import com.better.common.config.NoProtectedProperties;
import com.better.common.utils.CusAccessObjectUtil;
import com.better.common.utils.SessionUtils;
import com.better.util.HttpContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 切面类
 * 实现Web层的日志切面
 */
@Aspect
@Component
public class HttpAspect {
    private final static Logger LOGGER = LoggerFactory.getLogger(HttpAspect.class);
    @Autowired
    private ExceptionHandle exceptionHandle;
    @Autowired
    private NoProtectedProperties noProtectedProperties;

    @Pointcut("execution(public * com.better.frontend.controller..*.*(..)) || execution(public * com.better.common.jwtauth..*.*Controller.*(..))")
    public void webLog() {

    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
       // ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request =  HttpContextUtils.getHttpServletRequest();
        LOGGER.info("URL : " + request.getRequestURL().toString());
        LOGGER.info("HTTP_METHOD : " + request.getMethod());
        LOGGER.info("IP : " + CusAccessObjectUtil.getIpAddress(request));
        LOGGER.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        LOGGER.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            //ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request =  HttpContextUtils.getHttpServletRequest();
           String[] noAuthPath=noProtectedProperties.getAuthPath();
            boolean isAuth = true;
            String requestUrl = request.getRequestURL().toString();
            for (String str : noAuthPath) {
                if (requestUrl.contains(str)) {
                    isAuth = false;
                    break;
                }
            }
            //过滤掉不许鉴权的接口
            if (isAuth) {
                SessionUtils.getUserInfo();
            }
            Object result = proceedingJoinPoint.proceed();
            return result;
        } catch (DescribeException e) {
            return exceptionHandle.exceptionGet(e);
        } finally {
            long end = System.currentTimeMillis();
            LOGGER.info("+++++around " + proceedingJoinPoint + "\t Use time : " + (end - start) + " ms!");
        }
    }

    @AfterReturning(pointcut = "webLog()", returning = "object")//打印输出结果
    public void doAfterReturing(Object object) {
        if(object!=null){
            LOGGER.info("response={}", ToStringBuilder.reflectionToString(object));
        }
    }
}
